package org.ushio.nchu_22201408.service.Impl;

import org.ushio.common_module.entity.User;
import org.ushio.nchu_22201408.mapper.UserMapper;
import org.ushio.nchu_22201408.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ushio.nchu_22201408.util.JwtUtil;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User findUserByPhoneNumber(String phoneNumber) {
        return userMapper.findUserByPhoneNumber(phoneNumber);
    }
    @Override
    public boolean judgeFindUserByPhoneNumber(String phoneNumber) {
        if(userMapper.findUserByPhoneNumber(phoneNumber) != null){
            return true;
        }else{
            return false;
        }
    }
    // 实现其他业务方法
    @Override
    public boolean registerUser(User user) {
        String encryptedPassword = encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        User existingUser = findUserByPhoneNumber(user.getPhoneNumber());
        if (existingUser == null) {
            userMapper.insertUser(user);
            return true;
        }
        return false;
    }

    @Override
    public boolean loginUser(String phoneNumber, String password) {
        User user = findUserByPhoneNumber(phoneNumber);
        System.out.println(user);
        if (user != null) {
            return user.getPassword().equals(encryptPassword(password));
        }
        return false;
    }

    private String encryptPassword(String password) {
        return password;
    }
    @Override
    public String generateToken(String phoneNumber, String password) {
        User user = findUserByPhoneNumber(phoneNumber);
        if (user != null && user.getPassword().equals(encryptPassword(password))) {
            return new JwtUtil().generateToken(phoneNumber);
        }
        return null;
    }
    @Override
    public boolean updateUser(User user) {
        String encryptedPassword = encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        int updated = userMapper.updateUser(user);
        return updated > 0;
    }
    @Override
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }
    @Override
    public boolean banUser(String phoneNumber) {
        User user = findUserByPhoneNumber(phoneNumber);
        System.out.println(user);
        if (user != null && user.getBanStatus() == 0) {
            user.setBanStatus(1);
            userMapper.updateBanStatus(phoneNumber, user.getBanStatus());
            return true;
        } else if (user != null && user.getBanStatus() == 1) {
            return false;
        } else {
            return false;
        }
    }

}